<?php
/**
 * nutzp 代码生成工具 1.0
 * @author Leo Ning 2010-09-09
 */
define ( 'MGR', dirname ( __FILE__ ) );
echo <<<EOF
=================================================
=== Nutzp Code Tool V1.0       (Leo Ning 2010)===
=================================================

EOF;
if (! empty ( $argv ) && count ( $argv ) >= 2) {
	array_shift ( $argv );
	$appdir = array_shift ( $argv );
	if (! preg_match ( '/^(([a-z]:)|\/).*/i', $appdir )) {
		$appdir = MGR . '/../../' . $appdir;
	}
	$appname = empty ( $argv ) ? 'another nutzp webapp' : array_shift ( $argv );
	
	if (! is_dir ( $appdir )) {
		echo "Creating appdir {$appdir} ...";
		if (! mkdir ( $appdir, 0777, true )) {
			echo " [failure].\n";
			die ();
		} else {
			echo " [success].\n";
		}
	}
	echo "\n\nCreating bootstrap script ...";
	$bootstrap = file_get_contents ( MGR . '/apptpl/bootstrap.tpl' );
	$bootstrap = str_replace ( '@appname@', $appname, $bootstrap );
	$bootstrap = str_replace ( '@nutz@', realpath ( MGR . '/../' ), $bootstrap );
	if (file_put_contents ( $appdir . '/bootstrap.inc', $bootstrap )) {
		echo " [success]\n";
	} else {
		echo " [failure]\n";
		die ();
	}
	echo "\nCreating apps directory ...\n";
	echo "\t apps ...\n";
	echo "\t\t Default/actions ...\n";
	if (! mkdir ( $appdir . '/apps/Default/actions/', 0777, true )) {
		echo "Creating apps directory [failure]\n";
		die ();
	}
	echo "\t\t Default/views ...\n";
	mkdir ( $appdir . '/apps/Default/views/', 0777, true );
	echo "\t etc ...\n";
	mkdir ( $appdir . '/etc/', 0777, true );
	echo "\t tmp ...\n";
	mkdir ( $appdir . '/tmp/', 0777, true );
	echo "\t html ...\n";
	mkdir ( $appdir . '/html/', 0777, true );
	echo "Creating apps directory [success]\n\n";
	
	echo "Creating Wellcome Page ...\n";
	echo "\t apps/Default/actions/Index.inc ...\n";
	file_put_contents ( $appdir . '/apps/Default/actions/Index.inc', file_get_contents ( MGR . '/apptpl/index_action.tpl' ) );
	echo "\t apps/Default/actions/Index.html ...\n";
	file_put_contents ( $appdir . '/apps/Default/views/Index.html', file_get_contents ( MGR . '/apptpl/index_view.tpl' ) );
	echo "\t html/index.php ...\n";
	file_put_contents ( $appdir . '/html/index.php', "<?php\ninclude '../bootstrap.inc';\nNutzp::run ( 'Default');\n" );
	echo "\t etc/ioc.xml ...\n";
	file_put_contents ( $appdir . '/etc/ioc.xml', file_get_contents ( MGR . '/apptpl/example_ioc.xml' ) );
	copy ( MGR . '/apptpl/.htaccess', $appdir . '/.htaccess' );
	echo "Creating Wellcome Page [success]\n";
	
	echo "\n\nCongratulations,Please create a virtual host or website which doc root point to " . realpath ( $appdir . '/html/' );
	echo "\n\nAfter that please visit the web. you will see 'Hello Nutzp!'.\n\n";
	echo "Enjoy it.\n\n";

} else {
	echo "Usage:appmgr.[bat|sh] appdir [appname]\n";
}